<script setup lang="ts">
  import { getOrderListSelectField } from '@/api/order'
  import { onMounted, ref } from 'vue'
  import _ from 'lodash'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import useMerchantOptionListService from '@/services/module/order/useMerchantOptionListService'
  import useOrderModuleOptionListService from '@/services/module/order/useOrderModuleOptionListService'
  import useNetworkOptionListService from '@/services/module/network/useNetworkOptionListService'

  const {
    orderModuleOptionList,
    getOrderModuleOptionListParam,
    getOrderModuleOptionListLoading,
    getOrderModuleOptionList,
  } = useOrderModuleOptionListService()
  const {
    merchantOptionList,
    getMerchantOptionListParam,
    getMerchantOptionListLoading,
    getMerchantOptionList,
  } = useMerchantOptionListService()
  const {
    networkOptionList,
    getNetworkOptionListParam,
    getNetworkOptionListLoading,
    getNetworkOptionList,
  } = useNetworkOptionListService()

  defineOptions({
    name: 'OrderListFilterComponent',
  })

  const emits = defineEmits<{
    (e: 'getList'): void
  }>()

  const filterForm = ref<OrderRequestParam.OrderList>({
    dateFieldType: 1,
    dateType: '',
    orderStartTime: '',
    orderEndTime: '',
    orderNo: '',
    goodsSearch: '',
    orderUserSearch: '',
    fieldSearch: '',
    fieldId: '',
    factoryIds: [],
    status: '',
    networkIds: [],
    moduleIds: [],
    sources: [],
    province: '',
    city: '',
    area: '',
    addresses: [],
    areas: [],
    childStatus: '',
    citys: [],
    empIds: [],
    empType: '',
    isHs: '',
    isHx: '',
    isPause: 0,
    limit: 0,
    maxServiceTime: '',
    minServiceTime: '',
    networkType: '',
    orderNodeTimeoutType: '',
    page: 0,
    provinces: [],
    serviceTimeType: '',
    statues: [],
    workLevelIds: [],
    statusList: [],
  })
  const dateRange = ref<Array<string>>([])
  const customFiledOptional = ref<Array<{ id: string; name: string; select: boolean }>>([])
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null)

  const handleDateRangeChange = () => {
    filterForm.value.orderStartTime = ''
    filterForm.value.orderEndTime = ''
    if (dateRange.value && dateRange.value.length >= 2) {
      filterForm.value.orderStartTime = dateRange.value[0]
      filterForm.value.orderEndTime = dateRange.value[1]
    }
    emits('getList')
  }

  const handleGetFactoryOptions = _.throttle((query: string) => {
    getMerchantOptionListParam.value.name = query
    getMerchantOptionList()
  }, 500)

  const handleGetNetworkOptions = _.throttle((keyword: string) => {
    getNetworkOptionListParam.value.name = keyword
    getNetworkOptionList()
  }, 600)

  const getOptions = async () => {
    const res = await getOrderListSelectField()
    customFiledOptional.value = res.data.data.rows
  }

  const handleChangeAddress = () => {
    if (singleAddressRef.value) {
      const useAddr = singleAddressRef.value.getSelectAddr()
      filterForm.value.addresses =
        (useAddr as Array<{ province: string; city: string; area: string; town: string }>) || []
      emits('getList')
    }
  }

  const onClearAddress = () => {
    filterForm.value.province = ''
    filterForm.value.area = ''
    filterForm.value.city = ''
    // filterForm.value.town = ''
    emits('getList')
  }

  const reset = () => {
    dateRange.value.length = 0
    if (singleAddressRef.value) {
      singleAddressRef.value.clearSelectAddr()
    }
    filterForm.value = {
      dateFieldType: 1,
      dateType: '',
      orderStartTime: '',
      orderEndTime: '',
      orderNo: '',
      goodsSearch: '',
      orderUserSearch: '',
      fieldSearch: '',
      fieldId: '',
      factoryIds: [],
      status: '',
      networkIds: [],
      moduleIds: [],
      sources: [],
      province: '',
      city: '',
      area: '',
      addresses: [],
      areas: [],
      childStatus: '',
      citys: [],
      empIds: [],
      empType: '',
      isHs: '',
      isHx: '',
      isPause: 0,
      limit: 0,
      maxServiceTime: '',
      minServiceTime: '',
      networkType: '',
      orderNodeTimeoutType: '',
      page: 0,
      provinces: [],
      serviceTimeType: '',
      statues: [],
      workLevelIds: [],
      statusList: [],
    }
  }

  const onDateTypeChange = () => {
    if ([2, 3, 4].includes(filterForm.value.dateType)) {
      emits('getList')
    }
  }

  const handleGetOrderTypeOptions = _.throttle((query: string) => {
    getOrderModuleOptionListParam.value.name = query
    getOrderModuleOptionList()
  }, 500)

  onMounted(() => {
    getOptions()
  })

  defineExpose({
    getFilter: () => {
      return { ...filterForm.value }
    },
    reset,
  })
</script>

<template>
  <div class="filter">
    <!-- 时间字段类型 -->
    <el-select v-model="filterForm.dateFieldType" placeholder="下单日期" style="width: 100px">
      <el-option label="报单日期" :value="1" />
      <el-option label="完工日期" :value="2" />
      <el-option label="结算日期" :value="3" />
    </el-select>

    <!--选择时间-->
    <el-select
      style="width: 110px"
      @change="onDateTypeChange"
      v-model="filterForm.dateType"
      placeholder="全部时间"
      clearable
      @clear="emits('getList')"
    >
      <el-option :value="2" label="今天" />
      <el-option :value="3" label="本周" />
      <el-option :value="4" label="本月" />
      <el-option :value="1" label="自定义时间" />
    </el-select>

    <!--日期范围-->
    <el-date-picker
      v-if="filterForm.dateType === 1"
      v-model="dateRange"
      type="daterange"
      :unlink-panels="true"
      value-format="YYYY-MM-DD"
      range-separator="到"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      style="width: 100px"
      @change="handleDateRangeChange"
    />

    <!--工单编号-->
    <el-input
      style="width: 140px"
      v-model="filterForm.orderNo"
      clearable
      placeholder="工单编号"
      @clear="emits('getList')"
      @keyup.enter="emits('getList')"
    />

    <!--关联商家-->
    <el-select
      @change="emits('getList')"
      @clear="emits('getList')"
      style="width: 180px"
      v-model="filterForm.factoryIds"
      placeholder="商家"
      filterable
      clearable
      remote-show-suffix
      multiple
      collapse-tags
      collapse-tags-tooltip
      :filter-method="handleGetFactoryOptions"
      :loading="getMerchantOptionListLoading"
    >
      <el-option
        v-for="factory in merchantOptionList"
        :key="factory.id"
        :label="factory.name"
        :value="factory.id"
      />
    </el-select>

    <!-- 客户名称/手机号/地址 -->
    <el-input
      clearable
      v-model="filterForm.orderUserSearch"
      placeholder="客户名称/手机号/地址"
      style="width: 180px"
      @clear="emits('getList')"
      @keyup.enter="emits('getList')"
    />

    <SingleAddress
      style="width: 260px"
      ref="singleAddressRef"
      @value-change="handleChangeAddress"
      @clear="onClearAddress"
      checkStrictly
    />

    <!-- 工单状态 -->
    <el-select
      v-model="filterForm.statusList"
      style="width: 180px"
      placeholder="工单状态"
      @change="emits('getList')"
      clearable
      @clear="emits('getList')"
      multiple
      collapse-tags
      collapse-tags-tooltip
      :max-collapse-tags="1"
    >
      <el-option label="待派单" :value="1" />
      <el-option label="待服务商确认" :value="2" />
      <el-option label="处理中" :value="3" />
      <el-option label="已完成" :value="4" />
      <el-option label="已取消" :value="5" />
      <el-option label="结单审核" :value="1001" />
      <el-option label="待核销" :value="2001" />
      <el-option label="待核实上门时间" :value="2002" />
      <el-option label="已挂起" :value="2000" />
    </el-select>

    <!-- 工单网点 -->
    <el-select
      v-model="filterForm.networkIds"
      collapse-tags
      collapse-tags-tooltip
      placeholder="网点"
      style="width: 180px"
      filterable
      clearable
      remote-show-suffix
      multiple
      :filter-method="handleGetNetworkOptions"
      :loading="getNetworkOptionListLoading"
      @change="emits('getList')"
      @clear="emits('getList')"
    >
      <el-option
        v-for="item in networkOptionList"
        :key="item.id"
        :value="item.id"
        :label="item.name"
      />
    </el-select>

    <!-- 工单类型 -->
    <el-select
      style="width: 180px"
      v-model="filterForm.moduleIds"
      :loading="getOrderModuleOptionListLoading"
      :filter-method="handleGetOrderTypeOptions"
      clearable
      filterable
      placeholder="工单类型"
      multiple
      collapse-tags
      collapse-tags-tooltip
      remote-show-suffix
      @change="emits('getList')"
      @clear="emits('getList')"
    >
      <el-option
        v-for="mod in orderModuleOptionList"
        :key="mod.name"
        :disabled="mod.select"
        :label="mod.name"
        :value="mod.id"
      />
    </el-select>

    <!-- 工单来源 -->
    <el-select
      style="width: 160px"
      v-model="filterForm.sources"
      @change="emits('getList')"
      @clear="emits('getList')"
      placeholder="工单来源"
      multiple
      collapse-tags
      collapse-tags-tooltip
      clearable
    >
      <el-option :label="'平台系统报单'" :value="1" />
      <el-option :label="'扫码保单'" :value="2" />
      <el-option :label="'小程序报单'" :value="3" />
      <el-option :label="'APP报单'" :value="4" />
      <el-option :label="'Excel导入报单'" :value="5" />
      <el-option :label="'品牌商家'" :value="6" />
      <el-option :label="'平台代商家报单'" :value="7" />
    </el-select>

    <!--搜索商品品牌/名称/型号-->
    <el-input
      clearable
      v-model="filterForm.goodsSearch"
      placeholder="商品品牌/名称/型号"
      style="width: 140px"
      @clear="emits('getList')"
      @keyup.enter="emits('getList')"
    />

    <!--关键字-->
    <el-input
      clearable
      v-model="filterForm.fieldSearch"
      placeholder="关键字"
      style="width: 260px"
      @clear="emits('getList')"
      @keyup.enter="emits('getList')"
    >
      <template #prepend>
        <el-select
          clearable
          class="item-select"
          v-model="filterForm.fieldId"
          placeholder="自定义字段"
          style="width: 120px"
          @clear="emits('getList')"
        >
          <el-option
            v-for="item in customFiledOptional"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </template>
    </el-input>

    <slot></slot>
  </div>
</template>

<style lang="scss" scoped>
  :deep(.el-date-editor) {
    height: 28px !important;
  }

  .filter {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
  }

  .el-select__selection {
    flex-wrap: nowrap;
  }
</style>
